package com.ithe.ssmandmg.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ithe.core.constant.SmsKey;
import com.ithe.core.exception.BizException;
import com.ithe.ssmandmg.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

import static com.ithe.core.constant.SmsKey.REGISTER_EXPIRE;
import static com.ithe.core.constant.SmsKey.REGISTER_SMS;

/**
 * Created by zxd on 2022/5/12
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {


    @Autowired
    private RedisTemplate redisTemplate;




    @Override
    public void sendRegisterSms(String phone) {
        //1.判空
        if (StringUtils.isEmpty(phone)){
            log.error("手机号码不能为空");
          //  throw new BizException();
            throw new BizException(ResultCode.USER_NOT_EXIST);
        }
        log.info("发送注册信息手机号码为：{}",phone);
        //2.判断手机号码是否存在
//        if (userRepository.findUserByPhone(phone)!=null){
//
//            log.error("手机号码已经注册");
//            throw new BizException(ResultCode.PHONE_EXIST);
//        }
        //3.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4.服务器存储验证码
        redisTemplate.boundValueOps(REGISTER_SMS+phone).set(code);

        //5.设置失效时间
        redisTemplate.boundValueOps(REGISTER_SMS+phone).expire(REGISTER_EXPIRE, TimeUnit.SECONDS);

        log.info("注册发送的验证码：{}，手机号码:{}",code,phone);
        //6.发送短信
//        SendSmsResponse sendSmsResponse = SendSms.sendSms(phone, code);
//        if (sendSmsResponse.getCode().equals("ok")){
//            log.error("短信发送失败!");
//            throw new CustomerException(MessageCode.SEND_MESSAGE_FAIL);
//        }
    }

    @Override
    public void sendLoginSms(String phone)  {

        //一键登录 有没有账号都可以发送短信
        //发送登录  没有注册账号就不行
        //发送注册短信 注册了就不行

        //1.生成验证码
//        StringBuilder sb=new StringBuilder();
//        for(int i=0;i<6;i++){
//            sb.append(new Random().nextInt(10));
//        }

        //生成的验证码
        String code = RandomUtil.randomNumbers(6);

        log.info("code is {}:",code);

        //2.服务器存储验证码
        redisTemplate.boundValueOps(SmsKey.LOGIN_SMS +phone).set(code);

        //3.设置失效时间
        redisTemplate.boundValueOps(SmsKey.LOGIN_SMS +phone).expire(5*60, TimeUnit.SECONDS);

        //4.发送短信给用户

//        SendSmsResponse sendSmsResponse = SendSms.sendSms(phone, code);
        //6.发送短信
//        if (sendSmsResponse.getCode().equals("ok")){
//            log.error("短信发送失败!");
//
//        }
    }

}
